package com.gf.common.util;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.imageio.ImageIO;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import com.gf.base.type.FileType;

/**
 * 文件上传存储类
 * 
 * @author zhuguifeng
 * 
 */
public class FileHelper {

	// 医生证件存储的目录
	private final static String FILEPATH_OF_LICENSE = "imageUpload/license/";

	// 身份证
	private final static String FILEPATH_OF_ID_CARD = "imageUpload/idCard/";

	// mp3
	// private final static String FILEPATH_OF_MP3 = "imageUpload/mp3/";

	// vidio
	// private final static String FILEPATH_OF_VIDEO = "imageUpload/video/";

	// 头像
	private final static String FILEPATH_OF_POTRAIT = "imageUpload/potrait/";

	// 定义允许上传的图片类型
	@SuppressWarnings("serial")
	private final static ArrayList<String> IMAGE_TYPE = new ArrayList<String>() {
		{
			add(".jpg");
			add(".jpeg");
			add(".png");
			add(".bmp");
		}
	};
	// 证件图片大小 <=2M
	private final static long IMAGE_SIZE = 2 * 1024 * 1024;
	// 头像大小
	private final static int IMAGE_POTRAIT_WIDTH = 100;
	private final static int IMAGE_POTRAIT_HEIGTH = 100;

	/**
	 * 验证上传的格式是否符合要求<br>
	 * 不同类型有不同的要求
	 * 
	 * @param file
	 * @return 成功返回:0<br>
	 *         格式不符合要求:-1;<br>
	 *         大小过大:-2<br>
	 */
	public static int validate(MultipartFile file, FileType fileType) {
		return 1;
	}

	/**
	 * 存储
	 * 
	 * @param inputStream
	 *            要存储的文件流
	 * @param newName
	 *            新的文件名
	 * @param filePath
	 *            新的文件要存储的位置
	 * @return 成功：true
	 */
	private static boolean save(InputStream inputStream, File savefile,
			FileType fileType) {

		try {
			FileOutputStream out = new FileOutputStream(savefile);

			FileCopyUtils.copy(inputStream, out);
			out.flush();

			inputStream.close();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	/**
	 * 存储医生上传的证件
	 * 
	 * @return 成功 返回路径 失败 null;
	 * @throws IOException
	 * 
	 */
	public static String saveLicenceOfDoctor(MultipartFile file)
			throws IOException {

		File dir = new File(WebHelper.getRealPath() + FILEPATH_OF_LICENSE);

		if (!dir.exists()) {
			dir.mkdirs();// 递归创建目录
		}
		String newName = createFileName(getSuffix(file));
		File savefile = new File(dir, newName);

		// boolean result = save(file.getInputStream(), savefile,
		// FileType.LICENSE);
		//
		// if (result) {
		// return FILEPATH_OF_LICENSE + newName;
		// } else {
		// return null;
		// }
		return null;
	}

	/**
	 * 存储上传的身份证件
	 * 
	 * @return 成功 返回路径 失败 null;
	 * @throws IOException
	 * 
	 */
	public static String saveIdCard(MultipartFile file) throws IOException {

		File dir = new File(WebHelper.getRealPath() + FILEPATH_OF_ID_CARD);

		if (!dir.exists()) {
			dir.mkdirs();// 递归创建目录
		}
		String newName = createFileName(getSuffix(file));
		File savefile = new File(dir, newName);

		// boolean result = save(file.getInputStream(), savefile,
		// FileType.ID_CARD);
		//
		// if (result) {
		// return FILEPATH_OF_ID_CARD + newName;
		// } else {
		// return null;
		// }
		return null;
	}

	/**
	 * 返回存储的相对地址
	 * 
	 * @param file
	 * @return 失败返回Nulls
	 */
	public static String savePotrait(MultipartFile file) {
		File dir = new File(WebHelper.getRealPath() + FILEPATH_OF_POTRAIT);
		if (!dir.exists()) {
			dir.mkdirs();
		}

		String newName = createFileName(getSuffix(file));
		File saveFile = new File(dir, newName);
		if (resizeImageAndSave(file, IMAGE_POTRAIT_WIDTH, IMAGE_POTRAIT_HEIGTH,
				saveFile)) {
			return FILEPATH_OF_POTRAIT + newName;
		} else {
			return null;
		}
	}

	/**
	 * 对图片进行resize
	 * 
	 * @param file
	 *            原文件
	 * @param newWidth
	 * @param newHeight
	 * @param newFile
	 *            新的文件地址：如new File("c:\\image\\mkyong_hint_png.jpg")
	 * @return 成功 true 失败 false
	 */
	private static boolean resizeImageAndSave(MultipartFile file, int newWidth,
			int newHeight, File newFile) {
		BufferedImage originalImage, resizedImage = null;
		try {
			originalImage = ImageIO.read(file.getInputStream());

			Image image = originalImage.getScaledInstance(IMAGE_POTRAIT_WIDTH,
					IMAGE_POTRAIT_HEIGTH, Image.SCALE_SMOOTH);
			int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
					: originalImage.getType();
			resizedImage = new BufferedImage(IMAGE_POTRAIT_WIDTH,
					IMAGE_POTRAIT_HEIGTH, type);

			Graphics g = resizedImage.createGraphics();
			g.drawImage(image, 0, 0, null);
			g.dispose();

			String imageType = getSuffix(file).substring(1);
			return ImageIO.write(resizedImage, imageType, newFile);

		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}

	}

	/**
	 * 生成唯一性的名字名 例： 23423423423.jpg
	 * 
	 * @return
	 */
	private static synchronized String createFileName(String suffix) {
		String filename = "";

		filename = System.currentTimeMillis() + ""
				+ (int) (1000 * Math.random()) + suffix;

		return filename;
	}

	/**
	 * 得到文件名的后缀 小写
	 * 
	 * @param file
	 * @return 文件类型 包括"."
	 */
	private static String getSuffix(MultipartFile file) {
		String name = file.getOriginalFilename();

		return name.substring(name.lastIndexOf("."), name.length())
				.toLowerCase();
	}

}
